﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Softserve.Pottery.Store.Domains;

namespace Pottery.Frontend.Models
{
    public class Cart
    {
        #region Actions with a cart
        
        /// <summary>
        /// Add item to a cart
        /// </summary>
        /// <param name="product"></param>
        /// <param name="quantity"></param>
        public void AddItem(Product product, int quantity)
        {
            CartLine line = lineCollection
                .Where(p => p.Product.Id == product.Id)
                .FirstOrDefault();

            if (line == null)
            {
                lineCollection.Add(new CartLine
                {
                    Product = product,
                    Quantity = quantity
                });
            }
            else
            {
                line.Quantity += quantity;
            }
        }

        /// <summary>
        /// Add item to a cart
        /// </summary>
        /// <param name="product"></param>
        public void AddItem(Product product)
        {
            AddItem(product, 1);
        }

        /// <summary>
        /// Remove a product line from a cart
        /// </summary>
        /// <param name="product"></param>
        public void RemoveItem(Product product)
        {
            lineCollection.RemoveAll(l => l.Product.Id == product.Id);
        }

        /// <summary>
        /// Clear a cart
        /// </summary>
        public void Clear()
        {
            lineCollection.Clear();
        }

        public void EditItem(int productId, int quantity)
        {
            CartLine line = lineCollection
                .Find(l => l.Product.Id == productId);

            if (line == null)
            {
                line.Quantity = quantity;
            }
        }

        public IEnumerable<CartLine> Lines
        {
            get { return lineCollection; }
        }

        #endregion

        #region Private fields

        private List<CartLine> lineCollection = new List<CartLine>();

        #endregion
    }

    /// <summary>
    /// Class of lines in a cart
    /// </summary>
    public class CartLine
    {
        /// <summary>
        /// A product for getting to cart
        /// </summary>
        public Product Product { get; set; }

        /// <summary>
        /// Quantity of  the product
        /// </summary>
        public int Quantity { get; set; }
    }
}